package com.shlh.saas.controller;

import com.shlh.saas.common.Result;
import com.shlh.saas.common.UserContext;
import com.shlh.saas.entity.User;
import com.shlh.saas.entity.UserBalance;
import com.shlh.saas.entity.VipPackage;
import com.shlh.saas.service.AuthService;
import com.shlh.saas.service.UserBalanceService;
import com.shlh.saas.service.UserService;
import com.shlh.saas.service.VipPackageService;
import com.shlh.saas.service.PaymentOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * VIP套餐控制器
 */
@RestController
@RequestMapping("/vip")
public class VipPackageController {
    
    private static final Logger log = LoggerFactory.getLogger(VipPackageController.class);

    @Autowired
    private VipPackageService vipPackageService;
    
    @Autowired
    private UserBalanceService userBalanceService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private PaymentOrderService paymentOrderService;
    
    @Autowired
    private PaymentController paymentController;
    
    /**
     * 获取所有VIP套餐列表
     * @return 套餐列表
     */
    @GetMapping("/packages")
    public Result<List<VipPackage>> getVipPackages() {
        log.info("接收到获取VIP套餐列表的请求");
        try {
            List<VipPackage> packages = vipPackageService.getAllValidPackages();
            log.info("成功返回VIP套餐列表，共{}个套餐", packages != null ? packages.size() : 0);
            return Result.success(packages);
        } catch (Exception e) {
            log.error("获取VIP套餐列表时发生异常: {}", e.getMessage(), e);
            return Result.error("获取VIP套餐列表失败，请稍后重试");
        }
    }
    
    /**
     * 获取用户的VIP状态
     * @return 用户VIP状态
     */
    @GetMapping("/status")
    public Result<Map<String, Object>> getVipStatus() {
        try {
            // 获取当前登录用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                return Result.error("未登录");
            }
            
            // 获取用户信息
            User user = userService.getById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            // 获取用户余额信息
            UserBalance userBalance = userBalanceService.getUserBalance(user.getPhone());
            
            Map<String, Object> data = new HashMap<>();
            if (userBalance != null) {
                data.put("vipLevel", userBalance.getVipLevel());
                data.put("vipExpireTime", userBalance.getVipExpireTime());
                data.put("exportQuotaRemaining", userBalance.getExportQuotaRemaining());
                data.put("viewRecordsRemaining", userBalance.getViewRecordsRemaining());
                data.put("reverseLookupRemaining", userBalance.getReverseLookupRemaining());
            } else {
                data.put("vipLevel", 0);
                data.put("vipExpireTime", null);
                data.put("exportQuotaRemaining", 0);
                data.put("viewRecordsRemaining", 5);
                data.put("reverseLookupRemaining", 0);
            }
            
            return Result.success(data);
        } catch (Exception e) {
            log.error("获取VIP状态时发生异常: {}", e.getMessage(), e);
            return Result.error("获取VIP状态失败，请稍后重试");
        }
    }
    
    /**
     * 获取指定套餐详情
     * @param id 套餐ID
     * @return 套餐详情
     */
    @GetMapping("/package/{id}")
    public Result<VipPackage> getVipPackageById(@PathVariable Long id) {
        log.info("接收到获取套餐ID={}的请求", id);
        try {
            VipPackage vipPackage = vipPackageService.getPackageById(id);
            if (vipPackage == null) {
                return Result.error("套餐不存在");
            }
            return Result.success(vipPackage);
        } catch (Exception e) {
            log.error("获取套餐详情时发生异常: {}", e.getMessage(), e);
            return Result.error("获取套餐详情失败，请稍后重试");
        }
    }
    
    /**
     * 购买VIP套餐
     * @param params 参数，包含packageId（套餐ID）和paymentType（支付方式：1-微信，2-支付宝）
     * @return 支付信息
     */
    @PostMapping("/purchase")
    @Transactional
    public Result<Map<String, Object>> purchaseVipPackage(@RequestBody Map<String, Object> params) {
        log.info("接收到购买VIP套餐的请求: {}", params);
        try {
            // 获取当前登录用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                return Result.error("未登录");
            }
            
            // 获取用户信息
            User user = userService.getById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            // 获取套餐ID
            if (!params.containsKey("packageId")) {
                return Result.error("参数错误，缺少packageId");
            }
            Long packageId = Long.parseLong(params.get("packageId").toString());
            
            // 获取支付方式
            Integer paymentType = params.containsKey("paymentType") ? 
                    Integer.parseInt(params.get("paymentType").toString()) : 2; // 默认支付宝
            
            // 创建订单参数
            Map<String, Object> orderParams = new HashMap<>();
            orderParams.put("packageId", packageId);
            orderParams.put("packageType", "VIP");
            orderParams.put("paymentType", paymentType);
            orderParams.put("phone", user.getPhone());
            
            // 调用支付控制器创建订单
            return paymentController.createOrderByPhone(orderParams);
        } catch (Exception e) {
            log.error("购买VIP套餐时发生异常: {}", e.getMessage(), e);
            return Result.error("购买VIP套餐失败，请稍后重试");
        }
    }
}